var _discountCoupons = {
    data() {
        return {
            __uploadProgress:0,
            /*发放区域*/
            grant_agent_items: [],
            /*发放区域用户*/
            grant_users_items: [],
            /*商家*/
            grant_ticket_business_items: [],
            /*产品*/
            grant_ticket_product_items: [],

            marketing_coupons_items: [],

            publics_huati_items:[],

            baseInfoConfig: {
                expiration_method: [],
                get_method: [],
                grant_errand_method: [],
                grant_ticket_method: [],
                grant_method: [],
                grant_platform: [],
                grant_status: []
            },
            grant_agent_loading: false,
            grant_users_loading: false,
            grant_ticket_business_loading: false,
            grant_ticket_product_loading: false,
            discountCoupons: {
                visible: false
            }
        }
    },
    methods: {
        uploadProgressEvent(event, file, fileList){
            this.uploadProgress = parseFloat(event.percent).toFixed(2);
            this.$Spin.show();
        },
        uploadExceededSizeEvent: function (file, fileList) {
            this.$Message.error('请上传5MB以内的文件');
        },
        uploadFormatErrorEvent: function (file, fileList) {
            this.$Message.error('请上传jpg,jpeg,png的文件');
        },

        discountCouponsSubmitEvent(name) {
            let __that = this;
            __that.submitLoading = true;
            __that.$refs[name].validate((valid) => {
                $.post('/admin.php/marketing/discount/submit_discount', __that.formValidate, function (res) {
                    if (res.code === 1) {
                        __that.$Message.success(res.msg);
                        setTimeout(function () {
                            __that.discountCouponsReturnPreviousPageEvent();
                        }, 1000);
                    } else {
                        __that.$Message.error(res.msg);
                        __that.submitLoading = false;
                    }
                });
            })
        },
        discountCouponsReturnPreviousPageEvent() {
            window.location.href = '/admin.php/marketing/index';
        },
        createDiscountCouponsOpenEvent() {
            let __that = this;
            __that.discountCoupons.visible = true;
        },

        getBaseInfoConfig() {
            let __that = this;
            $.post('/admin.php/marketing/discount/get_baseinfo_config', function (data) {
                __that.baseInfoConfig = data;
            });
        },

        getGrantAgentItems(query) {
            let __that = this;
            if (query === false) {
                __that.grant_users_items = [];
                __that.grant_users_loading = false;
                return false;
            }
            __that.grant_agent_items = [];
            __that.grant_agent_loading = true;
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/discount/get_grant_agent_items', {query: query}, function (data) {
                __that.grant_agent_items = data ? data : [];
                __that.grant_agent_loading = false;
            });
        },
        getGrantUsersItems(query) {
            let __that = this;
            if (query === false) {
                __that.grant_users_items = [];
                __that.grant_users_loading = false;
                return false;
            }
            __that.grant_users_items = [];
            __that.grant_users_loading = true;
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/discount/get_grant_users_items', {query: query}, function (data) {
                __that.grant_users_items = data ? data : [];
                __that.grant_users_loading = false;
            });
        },
        getGrantTicketBusinessItems(query) {
            let __that = this;
            if (query === false) {
                __that.grant_users_items = [];
                __that.grant_users_loading = false;
                return false;
            }
            __that.grant_ticket_business_items = [];
            __that.grant_ticket_business_loading = true;
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/discount/get_grant_ticket_business_items', {query: query}, function (data) {
                __that.grant_ticket_business_items = data ? data : [];
                __that.grant_ticket_business_loading = false;
            });
        },
        getGrantTicketProductItems(query) {
            let __that = this;
            if (query === false) {
                __that.grant_users_items = [];
                __that.grant_users_loading = false;
                return false;
            }
            __that.grant_ticket_product_items = [];
            __that.grant_ticket_product_loading = true;
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/discount/get_grant_ticket_product_items', {query: query}, function (data) {
                __that.grant_ticket_product_items = data ? data : [];
                __that.grant_ticket_product_loading = false;
            });
        },
        getMarketingCoupons(query) {
            let __that = this;
            if (query === false) {
                __that.marketing_coupons_items = [];
                return false;
            }
            __that.marketing_coupons_items = [];
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/common/get_marketing_coupons_lists', {query: query}, function (data) {
                __that.marketing_coupons_items = data ? data : [];
            });
        },
        getPublicsHuati(query) {
            let __that = this;
            if (query === false) {
                __that.publics_huati_items = [];
                return false;
            }
            __that.publics_huati_items = [];
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/common/get_publics_huati_items', {query: query}, function (data) {
                __that.publics_huati_items = data ? data : [];
            });
        },
        getAssociationItems(query) {
            let __that = this;
            if (query === false) {
                __that.association_items = [];
                return false;
            }
            __that.association_items = [];
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/common/get_association_items', {query: query}, function (data) {
                __that.association_items = data ? data : [];
            });
        },
    },

    mounted() {
        this.getBaseInfoConfig();
    },
};

var _discountCouponsV2 = {
    data: {
        editorOption: {
            modules: {
                toolbar: [
                    ['bold', 'italic', 'underline', 'strike', 'blockquote'],    //加粗，斜体，下划线，删除线
                    [{'header': 1}, {'header': 2}],        // 标题，键值对的形式；1、2表示字体大小
                    [{'list': 'ordered'}, {'list': 'bullet'}],     //列表
                    [{'script': 'sub'}, {'script': 'super'}],   // 上下标
                    [{'indent': '-1'}, {'indent': '+1'}],     // 缩进
                    [{'size': ['small', false, 'large', 'huge']}], // 字体大小
                    [{'header': [1, 2, 3, 4, 5, 6, false]}],     //几级标题
                    [{'color': []}, {'background': []}],     // 字体颜色，字体背景颜色
                    [{'align': []}],    //对齐方式
                    ['clean'],    //清除字体样式
                    ['image', 'video', 'link', 'clean']    //上传图片、上传视频
                ]
            },
            height: '200px',
            theme: 'snow'
        },
        uploadProgress:0,
        /*发放区域*/
        grant_agent_items: [],
        /*发放区域用户*/
        grant_users_items: [],
        /*商家*/
        grant_ticket_business_items: [],
        /*产品*/
        grant_ticket_product_items: [],

        marketing_coupons_items: [],

        publics_huati_items:[],

        baseInfoConfig: {
            expiration_method: [],
            get_method: [],
            grant_errand_method: [],
            grant_ticket_method: [],
            grant_method: [],
            grant_platform: [],
            grant_status: []
        },
        grant_agent_loading: false,
        grant_users_loading: false,
        grant_ticket_business_loading: false,
        grant_ticket_product_loading: false,
        discountCoupons: {
            visible: false
        }
    },
    methods: {
        createQuillEditorObject(element){
            let _this = this;
            setTimeout(function (){
                let _object = _this.$refs[element];
                console.log(_this.$refs);
                _object.quill.getModule('toolbar').addHandler('image', function (res, file){
                    _this.addRange = _object.quill.getSelection()
                    let fileInput = document.getElementById(element+'UploadButton')
                    fileInput.click()
                });
                _this[element+'UploadSuccess'] = function (res) {
                    if(res.code === 0){
                        _this.$Message.error(res.msg);
                    }else {
                        if (res.data.fullurl) {  // 将文件上传后的URL地址插入到编辑器文本中
                            let value = res.data.fullurl
                            let addRange = _object.quill.getSelection()
                            _object.quill.insertEmbed(addRange !== null ? addRange.index : 0, 'image', value, Quill.sources.USER)   // 调用编辑器的 insertEmbed 方法，插入URL
                        }
                    }
                    _this.$Spin.hide();
                }
            },300);
        },

        getAssociationItems(query) {
            let __that = this;
            if (query === false) {
                __that.association_items = [];
                return false;
            }
            __that.association_items = [];
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/common/get_association_items', {query: query}, function (data) {
                __that.association_items = data ? data : [];
            });
        },
        uploadProgressEvent(event, file, fileList){
            this.uploadProgress = parseFloat(event.percent).toFixed(2);
            this.$Spin.show();
         //   console.log(event);
        },
        uploadExceededSizeEvent: function (file, fileList) {
            this.$Message.error('请上传5MB以内的文件');
        },
        uploadFormatErrorEvent: function (file, fileList) {
            this.$Message.error('请上传jpg,jpeg,png的文件');
        },
        discountCouponsSubmitEvent(name) {
            let __that = this;
            __that.submitLoading = true;
            __that.$refs[name].validate((valid) => {
                $.post('/admin.php/marketing/discount/submit_discount', __that.formValidate, function (res) {
                    if (res.code === 1) {
                        __that.$Message.success(res.msg);
                        setTimeout(function () {
                            __that.discountCouponsReturnPreviousPageEvent();
                        }, 1000);
                    } else {
                        __that.$Message.error(res.msg);
                        __that.submitLoading = false;
                    }
                });
            })
        },

        discountCouponsReturnPreviousPageEvent() {
            window.location.href = '/admin.php/marketing/index';
        },
        createDiscountCouponsOpenEvent() {
            let __that = this;
            __that.discountCoupons.visible = true;
        },

        getBaseInfoConfig() {
            let __that = this;
            $.post('/admin.php/marketing/discount/get_baseinfo_config', function (data) {
                __that.baseInfoConfig = data;
            });
        },

        getGrantAgentItems(query) {
            let __that = this;
            if (query === false) {
                __that.grant_users_items = [];
                __that.grant_users_loading = false;
                return false;
            }
            __that.grant_agent_items = [];
            __that.grant_agent_loading = true;
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/discount/get_grant_agent_items', {query: query}, function (data) {
                __that.grant_agent_items = data ? data : [];
                __that.grant_agent_loading = false;
            });
        },
        getGrantUsersItems(query) {
            let __that = this;
            if (query === false) {
                __that.grant_users_items = [];
                __that.grant_users_loading = false;
                return false;
            }
            __that.grant_users_items = [];
            __that.grant_users_loading = true;
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/discount/get_grant_users_items', {query: query}, function (data) {
                __that.grant_users_items = data ? data : [];
                __that.grant_users_loading = false;
            });
        },
        getGrantTicketBusinessItems(query) {
            let __that = this;
            if (query === false) {
                __that.grant_users_items = [];
                __that.grant_users_loading = false;
                return false;
            }
            __that.grant_ticket_business_items = [];
            __that.grant_ticket_business_loading = true;
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/discount/get_grant_ticket_business_items', {query: query}, function (data) {
                __that.grant_ticket_business_items = data ? data : [];
                __that.grant_ticket_business_loading = false;
            });
        },
        getGrantTicketProductItems(query) {
            let __that = this;
            if (query === false) {
                __that.grant_users_items = [];
                __that.grant_users_loading = false;
                return false;
            }
            __that.grant_ticket_product_items = [];
            __that.grant_ticket_product_loading = true;
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/discount/get_grant_ticket_product_items', {query: query}, function (data) {
                __that.grant_ticket_product_items = data ? data : [];
                __that.grant_ticket_product_loading = false;
            });
        },
        getMarketingCoupons(query) {
            let __that = this;
            if (query === false) {
                __that.marketing_coupons_items = [];
                return false;
            }
            __that.marketing_coupons_items = [];
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/common/get_marketing_coupons_lists', {query: query}, function (data) {
                __that.marketing_coupons_items = data ? data : [];
            });
        },
        getPublicsHuati(query) {
            let __that = this;
            if (query === false) {
                __that.publics_huati_items = [];
                return false;
            }
            __that.publics_huati_items = [];
            query = ((query === true) ? '' : query);
            $.post('/admin.php/marketing/common/get_publics_huati_items', {query: query}, function (data) {
                __that.publics_huati_items = data ? data : [];
            });
        },
    },

    mounted() {
        this.getBaseInfoConfig();
    },
};

let _selectDiscountCouponsComponent = {
    data:{
        selectDiscountCoupons:{
            visible: false,
            spinShow: false,
            tablesLists:[],
            columns: [
                {type: 'selection', width: 60, align: 'center',fixed: 'left'},
                {title: '#ID', key: 'id', align: 'center', width: 60 ,fixed: 'left'},
                {title: '名称', key: 'name', align: 'center', width: 'auto',minWidth: 150,fixed: 'left'},
                {
                    title: '类型', key: 'type', align: 'center', width: 120, slot:'type'
                },
                {
                    title: '使用平台', key: 'grant_platform', align: 'center', width: 100, slot:'grant_platform'
                },
                {
                    title: '发放类型', key: 'distribution_text_text', align: 'center', width: 100
                },
                {
                    title: '满足金额', key: 'satisfy_amount', align: 'center', width: 100,slot:'satisfy_amount'
                },
                {
                    title: '优惠属性', key: 'amount', align: 'center', width: 150,slot:'amount'
                },

                {title: '发放总量', key: 'grant_total', align: 'center', width: 100},
                {
                    title: '发放时间', key: 'receive_start_time', align: 'center', width: 280,slot:'receive_start_time'
                },
                {
                    title: '使用时间', key: 'use_start_time', align: 'center', width: 280,slot:'use_start_time'

                }
            ],
            total: 0,
            emit: '',
            limit: 5,
            page: 1,
            searchType: 4,
            loading: false,
            selectiond:[],
            __selected:[],
            search: {
                keyword: '',
                status: '',
                page: 1,
                limit:5,
                size:5,
                get_method:0,
            },
        }
    },
    methods:{
        /* 打开model */
        selectDiscountCouponsOpenEvent(emit, selected, type) {
            let __that = this;
            __that.selectDiscountCoupons.visible = true;
            __that.selectDiscountCoupons.spinShow = true;
            __that.selectDiscountCoupons.__selected = selected;
            if(type){
                __that.selectDiscountCoupons.search.get_method = type;
                __that.selectDiscountCoupons.searchMethod = type;
            }
            __that.selectDiscountCoupons.emit = emit;
            __that.getDiscountCouponsListsEvent();
        },

        /* 关闭model */
        selectDiscountCouponsCloseEvent() {
            let __that = this;
            __that.selectDiscountCoupons.visible = false;
            __that.selectDiscountCoupons.spinShow = false;
            __that.tablesLists = [];
            __that.total = 0;
        },

        /* 选择事件 */
        selectDiscountCouponsSelectionEvent(selection) {
            let __that = this;
            __that.selectDiscountCoupons.selectiond = selection;
        },

        /* 搜索事件 */
        selectDiscountCouponsSearchEvent() {
            let __that = this;
            __that.selectDiscountCoupons.spinShow = true;
            __that.selectDiscountCoupons.search.page = 1;
            __that.getDiscountCouponsListsEvent();
        },

        /* 重置搜索 */
        selectDiscountCouponsResetEvent(){
            let __that = this;
            __that.selectDiscountCoupons.search = {
                keyword: '', page:1, size:5,limit:5,type:__that.selectDiscountCoupons.search.searchType
            };
            __that.selectDiscountCoupons.spinShow = true;
            __that.selectDiscountCoupons.search.page = 1;
            __that.getDiscountCouponsListsEvent();
        },

        /* 分页事件 */
        selectDiscountCouponsPageEvent(page) {
            let __that = this;
            __that.selectDiscountCoupons.spinShow = true;
            __that.selectDiscountCoupons.search.page = page;
            __that.getDiscountCouponsListsEvent();
        },

        selectDiscountCouponsConfirmEvent(){
            let __that = this;
            // if( __that.selectDiscountCoupons.selectiond.length < 1){
            //     __that.$Message.error('请选择优惠券');
            //     __that.selectDiscountCouponsCloseEvent();
            //     return false;
            // }
            var selected = [];
            __that.selectDiscountCoupons.selectiond.forEach(function (item) {
                selected.push({id: item.id, name: item.name});
            });
            if(typeof __that.selectDiscountCoupons.emit == 'function'){
                __that.selectDiscountCoupons.emit(selected);
            }
            __that.selectDiscountCouponsCloseEvent();
        },

        getDiscountCouponsListsEvent() {
            let __that = this;
            $.post('/admin.php/marketing/component/getDiscountCouponsListsEvent', __that.selectDiscountCoupons.search, function (data) {
                if(__that.selectDiscountCoupons.__selected.length > 0){
                    data.data.forEach(function (item) {
                        item._checked = false;
                        __that.selectDiscountCoupons.__selected.forEach(function (selected) {
                            if(item.id === selected.id){
                                item._checked = true;
                            }
                        })
                    });
                }
                __that.selectDiscountCoupons.tablesLists = data.data;
                __that.selectDiscountCoupons.total = data.total;
                __that.selectDiscountCoupons.spinShow = false;
            });
        }
    },
    mounted() {

    },
}

let _selectMinAppRoute = {
    data:{
        selectMinAppRoute:{
            visible: false,
            spinShow: false,
            tablesLists:[],
            columns: [
                {type: 'selection', width: 60, align: 'center',fixed: 'left'},
                {title: '#ID', key: 'id', align: 'center', width: 60 ,fixed: 'left'},
                {title: '名称', key: 'name', align: 'center', width: 'auto',minWidth: 150,slot:'label'},
                {title: '路由地址', key: 'page', align: 'center', minWidth: 100, slot:'page'},
            ],
            total: 0,
            emit: '',
            limit: 5,
            page: 1,
            loading: false,
            selectiond:[],
            __selected:[],
            __multiple:false,
            search: {
                keyword: '',
                status: '',
                page: 1,
                limit:5,
                size:5
            },
        }
    },
    methods:{
        /* 打开model */
        selectMinAppRouteOpenEvent(emit, selected, multiple) {
            let __that = this;
            console.log(selected);
            __that.selectMinAppRoute.visible = true;
            __that.selectMinAppRoute.spinShow = true;
            __that.selectMinAppRoute.__selected = selected;
            __that.selectMinAppRoute.__multiple = (multiple === true);
            __that.selectMinAppRoute.emit = emit;

            __that._selectMinAppRouteColumnsEvent();
            __that.getMinAppRouteListsEvent();
        },

        /* 关闭model */
        selectMinAppRouteCloseEvent() {
            let __that = this;
            __that.selectMinAppRoute.visible = false;
            __that.selectMinAppRoute.spinShow = false;
            __that.tablesLists = [];
            __that.total = 0;
        },

        _selectMinAppRouteColumnsEvent(){
            let __that = this;
            if(__that.selectMinAppRoute.__multiple){
                __that.selectMinAppRoute.columns = [
                    {type: 'selection', width: 60, align: 'center',fixed: 'left'},
                    {title: '#ID', key: 'id', align: 'center', width: 60 ,fixed: 'left'},
                    {title: '名称', key: 'name', align: 'center', width: 'auto',minWidth: 150,slot:'label'},
                    {title: '路由地址', key: 'page', align: 'center', minWidth: 100, slot:'page'},
                ]
            } else {
                __that.selectMinAppRoute.columns = [
                    {title: '#ID', key: 'id', align: 'center', width: 60 ,fixed: 'left'},
                    {title: '名称', key: 'name', align: 'center', width: 'auto',minWidth: 150,slot:'label'},
                    {title: '路由地址', key: 'page', align: 'center', minWidth: 100, slot:'page'},
                    {title: '操作', key: 'action', align: 'center', minWidth: 100, slot:'action'},
                ]
            }
        },
        /* 选择事件 */
        selectMinAppRouteSelectionEvent(selection, oldCurrentRow) {
            let __that = this;
            __that.selectMinAppRoute.selectiond = selection;
        },
        selectMinAppRouteHighlightClickEvent:function (selection, oldCurrentRow){
            let __that = this;
            if(typeof __that.selectMinAppRoute.emit == 'function'){
                __that.selectMinAppRoute.emit(selection);
            }
            __that.selectMinAppRouteCloseEvent();
        },
        /* 搜索事件 */
        selectMinAppRouteSearchEvent() {
            let __that = this;
            __that.selectMinAppRoute.spinShow = true;
            __that.selectMinAppRoute.search.page = 1;
            __that.getMinAppRouteListsEvent();
        },

        /* 重置搜索 */
        selectMinAppRouteResetEvent(){
            let __that = this;
            __that.selectMinAppRoute.search = {
                keyword: '', page:1, size:5,limit:5
            };
            __that.selectMinAppRoute.spinShow = true;
            __that.selectMinAppRoute.search.page = 1;
            __that.getMinAppRouteListsEvent();
        },

        /* 分页事件 */
        selectMinAppRoutePageEvent(page) {
            let __that = this;
            __that.selectMinAppRoute.spinShow = true;
            __that.selectMinAppRoute.search.page = page;
            __that.getMinAppRouteListsEvent();
        },

        selectMinAppRouteConfirmEvent(){
            let __that = this;
            var selected = [];
            if(__that.selectMinAppRoute.__multiple){
                __that.selectMinAppRoute.selectiond.forEach(function (item) {
                    selected.push(item);
                });
            }
            if(typeof __that.selectMinAppRoute.emit == 'function'){
                __that.selectMinAppRoute.emit(selected);
            }
            __that.selectMinAppRouteCloseEvent();
        },

        getMinAppRouteListsEvent() {
            let __that = this;
            $.post('/admin.php/advertisement/mammon/advertisementRouteItems', __that.selectMinAppRoute.search, function (data) {
                if(__that.selectMinAppRoute.__multiple ){
                    if(__that.selectMinAppRoute.__selected.length > 0){
                        data.data.forEach(function (item) {
                            item._checked = false;
                            __that.selectMinAppRoute.__selected.forEach(function (selected) {
                                if(item.id === selected.id){
                                    item._checked = true;
                                }
                            })
                        });
                    }
                }else {
                    if(__that.selectMinAppRoute.__selected.id){
                        data.data.forEach(function (item) {
                            item._highlight = false;
                            if(parseInt(item.id) === parseInt(__that.selectMinAppRoute.__selected.id)){
                                item._highlight = true;
                            }
                        });
                    }
                }
                __that.selectMinAppRoute.tablesLists = data.data;
                __that.selectMinAppRoute.total = data.total;
                __that.selectMinAppRoute.spinShow = false;
            });
        }
    },
    mounted() {

    },
}












window.$Tool = {
    fileIconItems: {
        doc: 'docx',
        docx: 'docx',
        csv: 'csv',
        zip: 'zip',
        pdf: 'pdf',
        ppt: 'ppt',
        pptx: 'ppt',
        xls: 'excel',
        xlsx: 'excel',
        txt: 'docx',
        file: 'docx',
        rar: 'zip',
        mp4: 'video',
        mp3: 'audio'
    },
    random: function (length) {
        length = length ? length : 16;
        var result = '';
        for (var i = 0; i < length; i++) {
            result += Math.floor(Math.random() * 16).toString(16)
        }
        return result.toUpperCase()
    },
    /**
     * 随机生成字符串
     * @param _charStr 指定生成字符串长度
     * @param len 指定生成字符串长度
     */
    getRandomString: function (_charStr, len) {
        var min = 0,
            max = _charStr.length - 1,
            _str = '';
        len = len || 15;
        for (var i = 0, index; i < len; i++) {
            index = (function (randomIndexFunc, i) {
                return randomIndexFunc(min, max, i, randomIndexFunc);
            })(function (min, max, i, _self) {
                let indexTemp = Math.floor(Math.random() * (max - min + 1) + min),
                    numStart = _charStr.length - 10;
                if (i == 0 && indexTemp >= numStart) {
                    indexTemp = _self(min, max, i, _self);
                }
                return indexTemp;
            }, i);
            _str += _charStr[index];
        }
        return _str;
    },

    getUrlParam: function (url, data) {
        if (!data) {
            return ''
        }
        var paramsStr = data instanceof Object ? $Tool.getQueryString(data) : data;
        return (url.indexOf('?') !== -1) ? paramsStr : '?' + paramsStr
    },

    getQueryData: function (data) {
        if (!data) {
            return null
        }
        if (typeof data === 'string') {
            return data
        }
        if (data instanceof FormData) {
            return data
        }
        return $Tool.getQueryString(data)
    },

    getQueryString: function (data) {
        var paramsArr = [];
        if (data instanceof Object) {
            Object.keys(data).forEach(function (key) {
                var val = data[key];
                paramsArr.push(encodeURIComponent(key) + '=' + encodeURIComponent(val))
            })
        }
        return paramsArr.join('&')
    },

    getObjectKeysToString: function (object) {
        return Object.keys(object).join(',');
    },

    getQueryVariable: function (item) {
        var query = window.location.search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == item) {
                return pair[1]
            }
        }
        return (false)
    },

    /*加密*/
    encrypt: function (str, KEY, IV) {
        if (!str) return false;
        KEY = KEY ? KEY : $_Config.request.key;
        IV = IV ? IV : $_Config.request.iv;
        // var key = CryptoJS.enc.Utf8.parse(KEY);
        // var iv = CryptoJS.enc.Utf8.parse(IV);
        // var encrypted = CryptoJS.AES.encrypt(str, key, {iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
        // str = encrypted.toString();
        // str = str.replace(/\+/g, "=A=");
        // str = str.replace(/&/g, "=B=");
        // str = str.replace(/\//g, "=C=");
        // return str

        var encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse(str), CryptoJS.enc.Utf8.parse(KEY), {
            iv: CryptoJS.enc.Utf8.parse(IV),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        })
        encrypted = CryptoJS.enc.Base64.stringify(encrypted.ciphertext);
        str = encrypted.toString();
        str = str.replace(/\+/g, "-A-");
        str = str.replace(/&/g, "-B-");
        str = str.replace(/\//g, "-C-");
        return str
    },

    /*解密*/
    decrypt: function (str, KEY, IV) {
        if (!str) return false;
        KEY = KEY ? KEY : $_Config.request.key;
        IV = IV ? IV : $_Config.request.iv;
        str = str.replace(/-A-/g, "+");
        str = str.replace(/-B-/g, "&");
        str = str.replace(/-C-/g, "/");
        // var key = CryptoJS.enc.Utf8.parse(KEY);
        // var iv = CryptoJS.enc.Utf8.parse(IV);
        // var decrypted = CryptoJS.AES.decrypt(str, key, {iv: iv, padding: CryptoJS.pad.Pkcs7});
        // return decrypted.toString(CryptoJS.enc.Utf8);
        let ciphertext = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Base64.parse(str));     // Base64解密
        let decryptResult = CryptoJS.AES.decrypt(ciphertext, CryptoJS.enc.Utf8.parse(KEY), {    //  AES解密
            iv: CryptoJS.enc.Utf8.parse(IV),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return decryptResult.toString(CryptoJS.enc.Utf8).toString();

    },

    isJsonStringify: function (str) {
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    return obj;
                } else {
                    return false
                }
            } catch (e) {
                return false
            }
        } else {
            return false
        }
    },

    jsonAndStringProcessing: function (str, def, key) {
        def = def ? def : '';
        if (!str || str === '') return def;
        if (typeof str == 'string') {
            try {
                var obj = JSON.parse(str);
                if (typeof obj == 'object' && obj) {
                    if (key) {
                        return (obj[key]) ? obj[key] : def;
                    }
                    return obj;
                } else {
                    return def
                }
            } catch (e) {
                return def
            }
        } else {
            return def;
        }
    },

    stringToArray: function (str) {
        return str.split(",").filter(function (n) {
            return n;
        });
    }
}

window.$Arrays = {
    InArray: function (key, items) {
        return (($.inArray(key, items) >= 0) ? true : false)
    },

    /*
    * arrayLookup
    * 从二维数组中 根据指定列获取某个字段的数据
    * $Arrays.arrayLookup(arrayItems, 'id', 12, 'name', '张三')
    * 从arrayItems 中获取 id=12 的 name 值，如果没有获取到默认张三
    * */
    arrayLookup: function (data, key, value, targetKey, def) {
        if (!data) return (def ? def : '---');
        var data_length = data.length;
        var targetValue = "";
        var targetValueArr = [];
        for (var i = 0; i < data_length; i++) {
            if (!data[i][key]) {
                break
            }

            if ($.isArray(value)) {
                if ($.inArray(data[i][key], value) >= 0) {
                    targetValueArr.push(data[i][targetKey]);
                }
            } else {
                if (data[i][key] == value) {
                    targetValue = targetKey ? data[i][targetKey] : data[i];
                    break
                }
            }
        }
        if ($.isArray(value) && targetValueArr.length > 0) {
            return targetValueArr.toString();
        }
        return targetValue ? targetValue : (def ? def : '---')
    },

    arrayLookupCascader: function (data, key, value, targetKey) {
        if (!data || !value) return '---';
        var values = value.split(",");
        var targetValue = "";
        $.each(data, function (s_key, val) {
            if (parseInt(val[key]) === parseInt(values[0])) {
                targetValue = val[targetKey] || '';
                if (values.length > 1 && values[1] && val.children) {
                    var target_two = $Arrays.arrayLookup(val.children, key, values[1]);
                    if (target_two) {
                        targetValue = targetValue + ' / ' + target_two[targetKey];
                    }
                    if (values.length > 2 && values[2] && target_two.children) {
                        targetValue = targetValue + ' / ' + $Arrays.arrayLookup(target_two.children, key, values[2], targetKey);
                    }
                }
            }
        });
        return targetValue ? targetValue : '---'
    },

    CountArrayValues: function (data, key) {
        if (!data) return 0;
        var data_length = data.length;
        var targetValue = 0;
        for (var i = 0; i < data_length; i++) {
            if (!data[i][key]) {
                break
            }
            targetValue = targetValue + data[i][key]
        }
        return targetValue ? targetValue : 0
    }
};

window.$Utils = {
    numToChinese: function (num) {
        var str = num.toString();
        var unit = ["", "十", "二十", "三十", "四十", "五十", "六十", "七十", "八十", "九十"];
        var digits = ['', "一", "二", "三", "四", "五", "六", "七", "八", "九"];
        var result = "";
        if (parseInt(str.length) === 1) {
            return digits[num];
        }
        if (parseInt(str.length) === 2) {
            return unit[str[0]] + digits[str[1]];
        }

        for (let i = 0; i < str.length; i++) {

            let digit = str[i];
            let numUnit = i;
            if (digit === ".") {
                continue;
            }
            if (digit === "0") {
                if (result.endsWith("零")) {
                    result = result.substring(0, result.length - 1);
                }
                if (i === str.length - 2 && str[i + 1] === "0") {
                    result += "零";
                } else if (numUnit !== 0) {
                    result += unit[numUnit] + "零";
                }
            } else {
                result += digits[digit - 1] + unit[numUnit];
            }
        }
        return result;
    },
    CalculateHowManyDaysAgo(time) {
        // time为时间戳
        time = time ? (((time + '').length < 11) ? (time * 1000) : time) : ((new Date()).getTime());
        var many_date = (((new Date().getTime()) - time) / 1000);

        if (many_date <= 30) return '刚刚';

        if (many_date <= 60) return Math.floor(many_date) + '秒前';

        if (many_date <= 3600) return Math.floor(many_date / 60) + '分钟前';

        if (many_date <= 86400) return Math.floor(many_date / 3600) + '个小时前';

        if (many_date <= 604800) return Math.floor(many_date / 86400) + '天前';

        if (many_date <= 2592000) return Math.floor(many_date / 604800) + '个星期前';

        if (many_date <= 15552000) return Math.floor(many_date / 2592000) + '个月前';

        if (many_date <= 31536000) return Math.floor(many_date / 2592000) + '个月前';

        return Math.floor(many_date / 31536000) + '年前';
    },
    cuttingStringLength: function (str, key, spl) {
        if ($.isArray(str)) return '---';
        if (!str) return '---';
        spl = spl ? spl : ',';
        var str_arr = str.split(spl);
        if (!str_arr || str_arr.length < 0) return '---';
        if (!str_arr[key]) return '---';
        return str_arr[key];
    },

    /*yyyy-MM-dd hh:mm:ss*/
    formatDate: function (fmt, time) {
        time = time ? time * 1000 : (new Date()).getTime();
        var date = new Date(parseInt(time));
        var o = {
            "M+": date.getMonth() + 1,
            "d+": date.getDate(),
            "h+": date.getHours(),
            "m+": date.getMinutes(),
            "s+": date.getSeconds(),
            "q+": Math.floor((date.getMonth() + 3) / 3),
            "S": date.getMilliseconds()
        };
        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (date.getFullYear() + "").substr(4 - RegExp.$1.length));
        for (var k in o)
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    },

    /*加密数据*/
    encrypt: function (str, KEY, IV) {
        if (!str) return false;
        KEY = KEY ? KEY : $Config.request.key;
        IV = IV ? IV : $Config.request.iv;
        var key = CryptoJS.enc.Utf8.parse(KEY);
        var iv = CryptoJS.enc.Utf8.parse(IV);
        var encrypted = CryptoJS.AES.encrypt(str, key, {
            iv: iv,
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        str = encrypted.toString();

        // str = str.replace(/=/g, "");
        str = str.replace(/\+/g, "=A=");
        str = str.replace(/&/g, "=B=");
        str = str.replace(/\//g, "=C=");
        return str;
    },

    /*解密数据*/
    decrypt: function (str, KEY, IV) {
        if (!str) return false;
        KEY = KEY ? KEY : $Config.request.key;
        IV = IV ? IV : $Config.request.iv;
        str = str.replace(/=A=/g, "+");
        str = str.replace(/=B=/g, "&");
        str = str.replace(/=C=/g, "/");

        var key = CryptoJS.enc.Utf8.parse(KEY);
        var iv = CryptoJS.enc.Utf8.parse(IV);
        var decrypted = CryptoJS.AES.decrypt(str, key, {
            iv: iv,
            padding: CryptoJS.pad.Pkcs7
        });
        return decrypted.toString(CryptoJS.enc.Utf8);
    },

    countStrLength: function (str) {
        var len = 0;
        for (var i = 0; i < str.length; i++) {
            if (str.charCodeAt(i) > 255) {
                len += 2;
            } else {
                len++;
            }
        }
        return len;
    },
};
